home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_11_11 / labrocca / magic.c < prev    next >
C/C++ Source or Header  |  1993-05-20  |  2KB  |  98 lines

  1. /*  MAGIC.C */
  2.  
  3. /*  Copyright 1993 by P. J. LaBrocca
  4.     All rights reserved.
  5.  
  6.     Compiles with Microsoft C versions 6, 7 & 8 (MS-DOS)
  7.     and Symantec THINK C 5 (Macintosh).
  8. */
  9.  
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <ctype.h>
  13.  
  14. #if defined( THINK_C )  /* Macintosh */
  15. #include <console.h>
  16. #endif
  17.  
  18. #include "dyn2darr.h"
  19.  
  20. /* Prototypes */
  21. void magic( int **, int );
  22. void show_mag( int ** );
  23.  
  24. /*****************
  25.     Solves a magic square puzzle as described in
  26.     D. E. Knuth, The Art of Computer Programming,
  27.     Volume 1/Fundamental Algorithms, 2nd Edition. p 158.
  28. ******************/
  29. void magic( int **mag, int size )
  30. {
  31.     int count = 1;
  32.     int r = 1;
  33.     int c = (size + 1) / 2;
  34.  
  35.     mag[r][c] =  count;
  36.     for( count = 2; count < (size * size + 1); ++count ) {
  37.         --r;
  38.         --c;
  39.         if( ((r == 0) && (c == 0)) || mag[r][c] != 0 ) {
  40.             ++c;
  41.             r += 2;
  42.         }
  43.         else if( r == 0 )
  44.             r = size;
  45.         else if( c == 0 )
  46.             c = size;
  47.         mag[r][c] = count;
  48.     }
  49. }
  50.  
  51. /*******************
  52.     Displays a magic square on screen.
  53.     show_mag doesn't need to be told how big
  54.     a side is. It gets the information
  55.     from the macro Dyn2dRows
  56. *********************/
  57. void show_mag( int **mag )
  58. {
  59.     unsigned r, c;
  60.     int sum = 0;
  61.  
  62.     putchar('\n');
  63.     for( r = 1; r < Dyn2dRows( mag ); ++r ) {
  64.         sum += mag[r][1];
  65.         for( c = 1; c < Dyn2dCols( mag ); ++c )
  66.             printf( "%4d", mag[r][c] );
  67.         putchar('\n');
  68.     }
  69.     printf( "\nMagic Sum is %d\n", sum );
  70. }
  71.  
  72. void main( int argc, char **argv )
  73. {
  74.     int side;
  75.     int **arr;         /* For D2D array */
  76.  
  77. #if defined( THINK_C )         /* Macintosh */
  78.     argc = ccommand( &argv );
  79. #endif
  80.     
  81.     if( argc != 2 || !isdigit( *argv[1] ) ) {
  82.         printf("\nUsage: magic 'positve odd integer'\n\n");
  83.         exit( 0 );
  84.     }
  85.  
  86.     side = atoi( argv[1] );
  87.     if( side % 2 == 0 ) {
  88.         printf("\nUsage: magic 'positve odd integer'\n\n");
  89.         exit( 0 );
  90.     }
  91.  
  92.     arr = (int **) Dyn2dArray( side + 1, side + 1, int );
  93.     magic( arr, side );
  94.     show_mag( arr );
  95.     free( arr );
  96. }
  97. /* End of File */
  98.